import PySimpleGUI as sg
import smtplib,os,base64,configparser,datetime
import gonggao,GUI_2rd,qian
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

name_list = {
    '李争华':{'email':'lizhenghua@hisense.com','tel':'13929193896'},
    '胡高祥':{'email':'hugaoxiang@hisense.com','tel':'18138666862'},
    '郑源富':{'email':'zhengyuanfu@hisense.com','tel':'18128222312'},
    '周景耀':{'email':'zhoujingyao@hisense.com','tel':'18138666355'},
    '甘佐前':{'email':'ganzuoqian@hisense.com','tel':'17762997727'},
    '王青':{'email':'wangqing9@hisense.com','tel':'18138665898'},
    '罗仕新':{'email':'luoshixin@hisense.com','tel':'13715542788'},
    '肖兰':{'email':'xiaolan@hisense.com','tel':'18022995628'},
    '黄冠辉':{'email':'huangguanhui@hisense.com','tel':'18022995138'},
    '霍佳胜':{'email':'huojiasheng@hisense.com','tel':'13715434141'},
    '何伟忠':{'email':'heweizhong@hisense.com','tel':'18138666823'},
    '莫海林':{'email':'mohailin@hisense.com','tel':'18029434436'},
    '韩国彪':{'email':'hanguobiao@hisense.com','tel':'14718443863'},
    '伍志森':{'email':'wuzhisen@hisense.com','tel':'13715546039'},
    '郑秋利':{'email':'zhengqiuli@hisense.com','tel':'18022999258'},
    '黄永勤':{'email':'huangyongqin@hisense.com','tel':'18138666820'}
}
teding_list =['非标设备制造','翅片模具制造','特种设备维保','压力管道/容器施工','电力工程施工']
context = {}

class SendMail(object):
    def __init__(self,username,passwd,recv,title,content,
                 file=None,ssl=False,
                 email_host='smtp.qq.com',port=25,ssl_port=465):
        '''
        :param username: 用户名
        :param passwd: 密码
        :param recv: 收件人，多个要传list ['a@qq.com','b@qq.com]
        :param title: 邮件标题
        :param content: 邮件正文
        :param file: 附件路径，如果不在当前目录下，要写绝对路径，默认没有附件
        :param ssl: 是否安全链接，默认为普通
        :param email_host: smtp服务器地址，默认为163服务器
        :param port: 非安全链接端口，默认为25
        :param ssl_port: 安全链接端口，默认为465
        '''
        self.username = username #用户名
        self.passwd = passwd #密码
        self.recv = recv #收件人，多个要传list ['a@qq.com','b@qq.com]
        self.title = title #邮件标题
        self.content = content #邮件正文
        self.file = file #附件路径，如果不在当前目录下，要写绝对路径
        self.email_host = email_host #smtp服务器地址
        self.port = port #普通端口
        self.ssl = ssl #是否安全链接
        self.ssl_port = ssl_port #安全链接端口
    def send_mail(self):
        msg = MIMEMultipart()
        #发送内容的对象
        if self.file:#处理附件的
            file_name = os.path.split(self.file)[-1]#只取文件名，不取路径
            try:
                f = open(self.file, 'rb').read()
            except Exception as e:
                raise Exception('附件打不开！！！！')
            else:
                att = MIMEText(f,"base64", "utf-8")
                att["Content-Type"] = 'application/octet-stream'
                #base64.b64encode(file_name.encode()).decode()
                new_file_name='=?utf-8?b?' + base64.b64encode(file_name.encode()).decode() + '?='
                #这里是处理文件名为中文名的，必须这么写
                att["Content-Disposition"] = 'attachment; filename="%s"'%(new_file_name)
                msg.attach(att)
        msg.attach(MIMEText(self.content))#邮件正文的内容
        msg['Subject'] = self.title  # 邮件主题
        msg['From'] = self.username  # 发送者账号
        msg['To'] = ','.join(self.recv)  # 接收者账号列表
        if self.ssl:
            self.smtp = smtplib.SMTP_SSL(self.email_host,port=self.ssl_port)
        else:
            self.smtp = smtplib.SMTP(self.email_host,port=self.port)
        #发送邮件服务器的对象
        self.smtp.login(self.username,self.passwd)
        try:
            self.smtp.sendmail(self.username,self.recv,msg.as_string())
            pass
        except Exception as e:
            print('出错了。。'+str(datetime.datetime.now()),e)
        else:
            print('发送成功！'+str(datetime.datetime.now()))
        self.smtp.quit()

class guiwindow(sg.Window):
    def __init__(self):
        super().__init__('自动生成工具')
        self.config = configparser.ConfigParser()
        try:
            self.config.read('config.ini')
            self.name_config = self.config['DEFAULT']['name']
            self.title_config = self.config['LAST']['title']
            self.teding_config = self.config['LAST']['teding']
        except:
            self.teding_config = teding_list[0]
            self.title_config = ''
        self.texts = ['项目名称:', '项目负责人:', '资质需求:', '技术要求简介:', '保证金金额:', '截止报名时间:', '开标时间:']
        self.getwindow()

    def getwindow(self):
        #sg.SetOptions(text_justification='center')
        self.layout=[
                [sg.Text(self.texts[0],size=(10,1)),sg.Input(key='title',default_text=self.title_config,size=(21,1))],
                [sg.Text(self.texts[1],size=(10,1)),sg.Combo(list(name_list.keys()),default_value=self.name_config,key='name',size=(19,1))],
                [sg.Text(self.texts[2], size=(10, 1)), sg.Combo(teding_list,key='teding',default_value=self.teding_config,size=(19,1))],
                [sg.Text(self.texts[3], size=(10, 1)), sg.Multiline(key='tec_context',size=(19,1))],
                [sg.Text(self.texts[4], size=(10, 1)), sg.Input(key='money',size=(14,1)),sg.Text('元')],
                [sg.Text(self.texts[5], size=(10, 1)), sg.Input(default_text=getDate(3),key='deadline',size=(14,1))],
                [sg.Text(self.texts[6], size=(10, 1)), sg.Input(default_text=getDate(6,True),key='open_date',size=(14,1))],
                [sg.Checkbox('自动发送邮件给刘有有与黄永勤',default=False,key='auto')],
                [sg.Button('生成招标公告',key='gonggao'),sg.Button('生成格式合同',key='hetong')]
                ]
        self.root = sg.Window('自动生成工具',self.layout)

def getDate(delay,isweekend=False):
    '''
    :param delay:延后多少天，截止时间一般为3天后，开标时间则是6天后。0天则选择当天
    :param isweekend: 开标时间要不能是周末，则选择True
    '''
    deadline = datetime.datetime.now() + datetime.timedelta(days=int(delay))
    deadline_date = str(deadline.year) + '年' + str(deadline.month) + '月' + str(deadline.day) + '日'
    while isweekend and deadline.weekday() in [5,6]:
        deadline = deadline + datetime.timedelta(days=1)
        deadline_date = str(deadline.year)+'年'+str(deadline.month)+'月'+str(deadline.day)+'日'
    return deadline_date


if __name__ == '__main__':
    window1 = guiwindow()
    window1.getwindow()
    win2_active = False

    while True:
        event1,values1 = window1.root.read()
        print(event1,values1)
        if event1 is None:
            break
        if event1 == 'gonggao':
            if values['title'] == window1.config['LAST']['title']:
                sg.Popup('本项目已经生成过一次招标公告，请确认是否重复',title='错误')
            else:
                for key in values.keys():
                    context.setdefault(key,values[key])

                context.setdefault('email', name_list[values['name']]['email'])
                context.setdefault('tec_context', values['tec_context'][0:-1])
                context.setdefault('money2', qian.verbose_price(int(values['money'])))
                context.setdefault('tel', name_list[values['name']]['tel'])
                context.setdefault('today', getDate(0))
                print(context)
                gg = gonggao.gonggao(context)
                result = gg.getGonggao()
                if result[0]:
                    config = configparser.ConfigParser()
                    config['DEFAULT']={'name':context['name']}
                    config['LAST'] = {'title':context['title'],
                                      'teding':context['teding'],
                                      }
                    with open('config.ini','w') as fp:
                        config.write(fp)
                    sg.Popup('成功生成招标公告')
                    if values['auto']:
                        m = SendMail(
                            username='huang.yongqin@qq.com',
                            passwd='udckfaycpwynbhbi',
                            recv=[context['email'], 'huangyongqin@hisense.com','huang.yongqin@163.com','liuyouyou1@hisense.com'],
                            title='招标公告，请查阅',
                            content='本邮件是自动发送，已生成的招标公告请见附件',
                            ssl=True,
                            file=result[1]
                        )
                        m.send_mail()
                else:
                    sg.Popup('错误')
        elif event1 == 'hetong'and not win2_active:
            for key in values1.keys():
                context.setdefault(key, values1[key])
            win2_active = True
            window1.root.Hide()
            window2 = GUI_2rd.GUI(context)
            while True:
                event2, values2 = window2.root.read()
                if event2 is None :
                    window2.root.Close()
                    win2_active = False
                    window1.root.UnHide()
                elif event2 in ['payment4','payment3','payment2','payment1']:
                    window2.setdefault(event2)





    window1.close()
